﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using zyconfig;
using zymarc;

namespace zyui
{
    public class SaveMarc
    {
        /// <summary>
        /// 检测MARC必备字段
        /// </summary>
        /// <param name="str">MarcTxt</param>
        /// <param name="strError">返回错误信息</param>
        /// <returns></returns>
        public static bool check(string str,out string strError)
        {
            bool f = true;
            bool flag = false;
            MarcConvert convert = new MarcConvert();
            convert.MarcText = str;
            string stre = "";
            using (DbOperHandler _open = new Common().Doh())
            {
                if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                    flag = true;
                if (flag)
                {
                    stre = "";
                }
                else
                {
                    _open.Reset();
                    _open.SqlCmd = "select * from Marc_B order by id";
                    DataTable dt = _open.GetDataTable();
                    foreach(DataRow drow in dt.Rows)
                    {
                        string s=  convert.GetASubField(drow["zd"].ToString(), drow["zzd"].ToString(), 1);
                        if (string.IsNullOrEmpty(s))
                        {
                            stre = "【" + drow["zd"].ToString() + drow["zzd"].ToString() + "】不能为空！";
                            f = false;
                            break;
                        }
                    }
                }
            }
            strError = stre;
            return f;
        }
        /// <summary>
        /// 更新检索项
        /// </summary>
        /// <param name="mainKey">主键码</param>
        /// <param name="kjm">库键码</param>
        public static void SaveForZjm(int mainKey,int kjm)
        {
            bool flag = false;
            MarcConvert convert = new MarcConvert();
            //convert.MarcText = Nmarc;
            using (DbOperHandler _open = new Common().Doh())
            {
                if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                    flag = true;
                string marc = string.Empty;
                if (flag)
                {
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKey;
                    marc = _open.GetField("MARC_DATA", "marc1").ToString();
                    if (string.IsNullOrEmpty(marc))
                        marc = _open.GetField("MARC_DATA", "marc2").ToString();
                    if (string.IsNullOrEmpty(marc))
                        marc = _open.GetField("MARC_DATA", "marc2").ToString();
                    if (!string.IsNullOrEmpty(marc))
                        convert.MarcText = marc;
                }
                else
                {
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKey;
                    marc = _open.GetField("馆藏书目库", "marc").ToString();
                    if (!string.IsNullOrEmpty(marc))
                    {
                        try
                        {
                            convert.ISOData = marc;
                            if (marc.Split('\x001e')[0].Length < 25)
                            {
                                convert.MarcText = marc;
                                convert.SetISOStr();
                                convert.SetISOtoMarc();
                            }
                            else
                            {
                                convert.SetISOtoMarc();
                            }
                        }
                        catch { }
                    }
                }
                if (!string.IsNullOrEmpty(convert.MarcText))
                {
                    _open.Reset();
                    _open.SqlCmd = "select 库键码 ,所属表,类型 from 检索途径定义 where 库键码=" + kjm + " group by 所属表,库键码,类型 order by 所属表";
                    DataTable dt = _open.GetDataTable();
                    string tName = string.Empty;
                    foreach (DataRow dRow in dt.Rows)
                    {
                        tName = dRow["所属表"].ToString().Trim();
                        int lx = Convert.ToInt32(dRow["类型"].ToString().Trim());
                        //Console.WriteLine(tName);
                        Bjstj book = new Bjstj();
                        List<string> flist = new List<string>();
                        List<string> nlist = new List<string>();
                        List<int> lxlist = new List<int>();
                        book.Tname = tName;
                        _open.Reset();
                        _open.SqlCmd = "select * from 检索途径生成方式 where 库键码=" + kjm + " and 所属表='" + tName + "' and 类型="+ lx +" order by 类型,MARC字段标识";
                        DataTable dtt = _open.GetDataTable();
                        foreach (DataRow dsRow in dtt.Rows)
                        {
                            string fildName = dsRow["表字段名"].ToString().Trim();
                            string zd = dsRow["MARC字段标识"].ToString().Trim();
                            string zzd = dsRow["子字段标识"].ToString().Trim();
                            string tzd = dsRow["同取子字段"].ToString().Trim();
                            string qzd = dsRow["其余字段"].ToString().Trim();
                            //string lx = dsRow["类型"].ToString().Trim();
                            string nr = convert.GetASubField(zd, zzd, 1);
                            if (fildName.EndsWith("分类号"))
                            {
                                string nr1 = convert.GetASubField(zd, zzd, 2);
                                if (!string.IsNullOrEmpty(nr1))
                                    nr += ":" + nr1;
                            }
                            if (!string.IsNullOrEmpty(tzd))
                            {
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(tzd.Substring(0, 1)))
                                {
                                    tzd = "," + tzd;
                                }
                                char[] chArray = tzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                            //Console.WriteLine(zd+":"+chArray[m].ToString() + ":" + nr);
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(qzd))
                            {
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(qzd.Substring(0, 1)))
                                {
                                    qzd = "," + qzd;
                                }
                                char[] chArray = qzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 5 != 0 && i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(nr))
                            {
                                //Console.WriteLine(nr);
                                if (fildName.Equals("题名缩写"))
                                {
                                    string[] nrs = nr.Split(new char[] { ' ' });
                                    nr = "";
                                    foreach (string str in nrs)
                                    {
                                        nr += str.Substring(0, 1).ToLower();
                                    }
                                    if (nr.Length > 16)
                                        nr = nr.Substring(0, 15);
                                }
                                flist.Add(fildName);
                                lxlist.Add(lx);
                                nlist.Add(nr);
                                //Console.WriteLine(zd + ":" + fildName + ":" + nr);
                            }
                        }
                        book.FList = flist;
                        book.LxList = lxlist;
                        book.NrList = nlist;
                        if (book.NrList.Count > 0)
                        {
                            //Console.WriteLine("内容不空:"+tName);
                            if (tName.IndexOf("检索") < 0)
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + mainKey;
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i]);
                                }
                                List<string> bflist = new List<string> { "标准编码", "索书号" };
                                if (!book.FList.Exists(t => t == "标准编码"))
                                {
                                    string isbn = convert.GetASubField("010", "a", 1);
                                    if (string.IsNullOrEmpty(isbn))
                                        isbn = convert.GetASubField("011", "a", 1);
                                    _open.AddFieldItem("标准编码", isbn);
                                }
                                try
                                {
                                    convert.SetISOStr();
                                    if (!flag)
                                        _open.AddFieldItem("marc", convert.MarcText);
                                }
                                catch { }
                                try { 
                                    _open.Update(tName);
                                    //Console.WriteLine("ygx:"+tName);
                                }
                                catch(Exception ex)
                                {
                                    Console.WriteLine(tName + ":" + ex.Message);
                                }
                                if (flag)
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + mainKey;
                                    _open.AddFieldItem("marc1", marc);
                                    _open.Update("MARC_DATA");
                                }
                            }
                            else
                            {
                                if (tName.Equals("检索索书号库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + mainKey;
                                    int bm = _open.Count("检索索书号库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string sh = book.NrList[i].Trim();
                                        if (bm > 0)
                                        {
                                            string ssh = _open.GetField("检索索书号库", "索书号").ToString().Trim();
                                            if (!ssh.Equals(sh))
                                            {
                                                _open.AddFieldItem(book.FList[i].ToString(), sh);
                                                //_open.AddFieldItem("类型", book.LxList[i]);
                                                _open.Update("检索索书号库");
                                            }
                                        }
                                        else
                                        {
                                            _open.AddFieldItem(book.FList[i].ToString(), sh);
                                            //_open.AddFieldItem("类型", book.LxList[i]);
                                            _open.Insert("检索索书号库");
                                        }
                                        i++;
                                    }
                                }
                                if (tName.Equals("检索编码库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + mainKey;
                                    int bm = _open.Count("检索编码库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string isbn = book.NrList[i].Trim();
                                        if (!string.IsNullOrEmpty(isbn))
                                        {
                                            string sisbn = SqlText.BuingISBNSept(SqlText.BarCodeToISBN(isbn.Replace("-", "")));
                                            _open.AddFieldItem(book.FList[i].ToString(), sisbn);
                                            _open.AddFieldItem("类型", book.LxList[i]);
                                        }
                                        i++;
                                    }
                                    if (i > 0)
                                    {
                                        if (bm > 0)
                                            _open.Update("检索编码库");
                                        else
                                        {
                                            _open.AddFieldItem("主键码", mainKey);
                                            _open.Insert("检索编码库");
                                        }
                                    }

                                }
                                if (tName.Equals("检索一对多库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = "主键码=" + mainKey + " and 类型="+lx;
                                    _open.Delete("检索一对多库");
                                    for (int i = 0; i < book.NrList.Count; i++)
                                    {
                                        _open.Reset();
                                        _open.AddFieldItem("主键码", mainKey);
                                        _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                        _open.AddFieldItem("类型", lx);
                                        _open.Insert("检索一对多库");
                                    }
                                }
                                /**
                                if (tName.Equals("检索多对多库"))
                                {
                                    _open.Reset();
                                    _open.SqlCmd = "select * from 检索联接库 where 主键码=" + mainKey;
                                    DataTable ddt = _open.GetDataTable();
                                    foreach (DataRow drow in ddt.Rows)
                                    {
                                        _open.Reset();
                                        _open.ConditionExpress = "子键码=" + drow["子键码"];
                                        _open.Delete("检索多对多库");
                                    }
                                    _open.Reset();
                                    _open.SqlCmd = "select * from 检索联接库 where 主键码=" + mainKey;
                                    _open.Delete("检索联接库");
                                    _open.Reset();
                                    int zjm = Convert.ToInt32(_open.MaxValue("检索多对多库", "子键码").ToString());
                                    for (int i = 0; i < book.NrList.Count; i++)
                                    {
                                        _open.Reset();
                                        _open.AddFieldItem("子键码", zjm + i + 1);
                                        _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                        _open.Insert("检索多对多库");
                                        _open.Reset();
                                        _open.AddFieldItem("主键码", mainKey);
                                        _open.AddFieldItem("子键码", zjm + i + 1);
                                        _open.Insert("检索联接库");
                                    }
                                }**/
                            }
                            //Console.WriteLine(JsonConvert.SerializeObject(book));
                        }
                    }
                }
            }
        }

        public static void SaveForZjmSsb(int mainKey, int kjm, string tName,string fildName,string jslx)
        {
            bool flag = false;
            MarcConvert convert = new MarcConvert();
            //convert.MarcText = Nmarc;
            using (DbOperHandler _open = new Common().Doh())
            {
                if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                    flag = true;
                string marc = string.Empty;
                if (flag)
                {
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKey;
                    marc = _open.GetField("MARC_DATA", "marc1").ToString();
                    if (string.IsNullOrEmpty(marc))
                        marc = _open.GetField("MARC_DATA", "marc2").ToString();
                    if (string.IsNullOrEmpty(marc))
                        marc = _open.GetField("MARC_DATA", "marc2").ToString();
                    if (!string.IsNullOrEmpty(marc))
                        convert.MarcText = marc;
                }
                else
                {
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + mainKey;
                    marc = _open.GetField("馆藏书目库", "marc").ToString();
                    if (!string.IsNullOrEmpty(marc))
                    {
                        try
                        {
                            convert.ISOData = marc;
                            //marc.Split('\x001e')[0].Length
                            if (marc.Split('\x001e')[0].Length<25)
                            {
                                convert.MarcText = marc;
                                convert.SetISOStr();
                                convert.SetISOtoMarc();
                            }
                            else
                            {
                                convert.SetISOtoMarc();
                            }
                            //Console.WriteLine("122:" + convert.MarcText);
                        }
                        catch { }
                    }
                }
                
                if (!string.IsNullOrEmpty(convert.MarcText))
                {
                    Bjstj book = new Bjstj();
                    List<string> flist = new List<string>();
                    List<string> nlist = new List<string>();
                    List<int> lxlist = new List<int>();
                    book.Tname = tName;
                    string sql = "select * from 检索途径生成方式 where 库键码=" + kjm + " and 所属表='" + tName + "' and 类型="+ jslx+" ";
                    if (tName.IndexOf("检索") < 0)
                        sql+= " and 表字段名 = '" + fildName + "' order by MARC字段标识,子字段标识";
                    else
                    {
                        fildName = "数据";
                        sql += " and 表字段名 = '" + fildName + "' order by MARC字段标识,子字段标识";
                    }
                    _open.Reset();
                    _open.SqlCmd = sql;
                    DataTable dtt = _open.GetDataTable();
                    foreach (DataRow dsRow in dtt.Rows)
                    {
                        string zd = dsRow["MARC字段标识"].ToString().Trim();
                        string zzd = dsRow["子字段标识"].ToString().Trim();
                        string tzd = dsRow["同取子字段"].ToString().Trim();
                        string qzd = dsRow["其余字段"].ToString().Trim();
                        //string lx = dsRow["类型"].ToString().Trim();
                        string nr = convert.GetASubField(zd, zzd, 1);
                        if (fildName.EndsWith("分类号"))
                        {
                            string nr1 = convert.GetASubField(zd, zzd, 2);
                            if (!string.IsNullOrEmpty(nr1))
                            {
                                nr += ":" + nr1;
                                //Console.WriteLine("字段内容:" +  nr);
                            }
                        }
                        
                        if (!string.IsNullOrEmpty(tzd))
                        {
                            Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                            if (!regExp.IsMatch(tzd.Substring(0, 1)))
                            {
                                tzd = "," + tzd;
                            }
                            char[] chArray = tzd.ToCharArray();
                            for (int i = 0; i < chArray.Length; i++)
                            {
                                if (i % 2 == 0)
                                {
                                    int m = i + 1;
                                    if (m < chArray.Length)
                                    {
                                        string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                        if (!string.IsNullOrEmpty(znr))
                                            nr += chArray[i].ToString() + znr;
                                        //Console.WriteLine(zd+":"+chArray[m].ToString() + ":" + nr);
                                    }
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(qzd))
                        {
                            Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                            if (!regExp.IsMatch(qzd.Substring(0, 1)))
                            {
                                qzd = "," + qzd;
                            }
                            char[] chArray = qzd.ToCharArray();
                            for (int i = 0; i < chArray.Length; i++)
                            {
                                if (i % 5 != 0 && i % 2 == 0)
                                {
                                    int m = i + 1;
                                    if (m < chArray.Length)
                                    {
                                        string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                        if (!string.IsNullOrEmpty(znr))
                                            nr += chArray[i].ToString() + znr;
                                    }
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(nr))
                        {
                            //Console.WriteLine(nr);
                            if (fildName.Equals("题名缩写"))
                            {
                                string[] nrs = nr.Split(new char[] { ' ' });
                                nr = "";
                                foreach (string str in nrs)
                                {
                                    nr += str.Substring(0, 1).ToLower();
                                }
                                if (nr.Length > 16)
                                    nr = nr.Substring(0, 15);
                            }
                            flist.Add(fildName);
                            lxlist.Add(Convert.ToInt32(jslx));
                            nlist.Add(nr);
                            //Console.WriteLine(zd + ":" + fildName + ":" + nr);
                        }
                    }
                    book.FList = flist;
                    book.LxList = lxlist;
                    book.NrList = nlist;
                    if (book.NrList.Count > 0)
                    {
                        if (tName.IndexOf("检索") < 0)
                        {
                            _open.Reset();
                            _open.ConditionExpress = " 主键码=" + mainKey;
                            for (int i = 0; i < book.NrList.Count; i++)
                            {
                                _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i]);
                            }
                            List<string> bflist = new List<string> { "标准编码", "索书号" };
                            if (!book.FList.Exists(t => t == "标准编码"))
                            {
                                string isbn = convert.GetASubField("010", "a", 1);
                                if (string.IsNullOrEmpty(isbn))
                                    isbn = convert.GetASubField("011", "a", 1);
                                _open.AddFieldItem("标准编码", isbn);
                            }
                            _open.Update(tName);
                        }
                        else
                        {
                            if (tName.Equals("检索索书号库"))
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + mainKey;
                                int bm = _open.Count("检索索书号库");
                                int i = 0;
                                while (i < book.NrList.Count)
                                {
                                    string sh = book.NrList[i].Trim();
                                    if (bm > 0)
                                    {
                                        string ssh = _open.GetField("检索索书号库", "数据").ToString().Trim();
                                        if (!ssh.Equals(sh))
                                        {
                                            _open.AddFieldItem(book.FList[i].ToString(), sh);
                                            _open.AddFieldItem("类型", book.LxList[i]);
                                            _open.Update("检索索书号库");
                                        }
                                    }
                                    else
                                    {
                                        _open.AddFieldItem(book.FList[i].ToString(), sh);
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                        _open.Insert("检索索书号库");
                                    }
                                    i++;
                                }
                            }
                            if (tName.Equals("检索编码库"))
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + mainKey;
                                int bm = _open.Count("检索编码库");
                                int i = 0;
                                while (i < book.NrList.Count)
                                {
                                    string isbn = book.NrList[i].Trim();
                                    if (!string.IsNullOrEmpty(isbn))
                                    {
                                        string sisbn = SqlText.BuingISBNSept(SqlText.BarCodeToISBN(isbn.Replace("-", "")));
                                        _open.AddFieldItem(book.FList[i].ToString(), sisbn);
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                    }
                                    i++;
                                }
                                if (i > 0)
                                {
                                    if (bm > 0)
                                        _open.Update("检索编码库");
                                    else
                                    {
                                        _open.AddFieldItem("主键码", mainKey);
                                        _open.Insert("检索编码库");
                                    }
                                }

                            }
                            if (tName.Equals("检索一对多库"))
                            {
                                _open.Reset();
                                _open.ConditionExpress = "主键码=" + mainKey +" and 类型="+jslx;
                                _open.Delete("检索一对多库");
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.Reset();
                                    _open.AddFieldItem("主键码", mainKey);
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                    _open.AddFieldItem("类型", book.LxList[i]);
                                    int m = _open.InsertU("检索一对多库");
                                    //Console.WriteLine(book.FList[i].ToString() + "::" + book.NrList[i].Trim()+"::"+book.LxList[i] +"::"+ m);
                                }
                            }
                            if (tName.Equals("检索多对多库"))
                            {
                                _open.Reset();
                                _open.SqlCmd = "select * from 检索联接库 where 主键码=" + mainKey;
                                DataTable ddt = _open.GetDataTable();
                                foreach (DataRow drow in ddt.Rows)
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = "子键码=" + drow["子键码"];
                                    _open.Delete("检索多对多库");
                                }
                                _open.Reset();
                                _open.SqlCmd = "select * from 检索联接库 where 主键码=" + mainKey;
                                _open.Delete("检索联接库");
                                _open.Reset();
                                int zjm = Convert.ToInt32(_open.MaxValue("检索多对多库", "子键码").ToString());
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.Reset();
                                    _open.AddFieldItem("子键码", zjm + i + 1);
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                    _open.AddFieldItem("类型", book.LxList[i]);
                                    _open.Insert("检索多对多库");
                                    _open.Reset();
                                    _open.AddFieldItem("主键码", mainKey);
                                    _open.AddFieldItem("子键码", zjm + i + 1);
                                    _open.Insert("检索联接库");
                                }
                            }
                        }
                        //Console.WriteLine(JsonConvert.SerializeObject(book));
                    }
                }

            }
        }
    }
}
